package com.motong.gongdan.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.motong.gongdan.entity.StockDetail;
import com.motong.gongdan.entity.StockMsg;
import com.motong.gongdan.mapper.StockDetailMapper;
import com.motong.gongdan.util.LoginUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author:fff
 * @time:2022/4/14
 */
@Service
public class StockDetailService extends ServiceImpl<StockDetailMapper, StockDetail> {

    @Resource
    private StockMsgService stockMsgService;

    /**
     * 纠正/保存出入库单
     *
     * @param difference   差值
     * @param productId    产品id
     * @param workReportId 报工id
     */
    public void rectifyStockByDifference(BigDecimal difference, Integer productId, String workReportId) {
        boolean isUpdate;
        StockMsg stockMsg = stockMsgService.getOne(new LambdaQueryWrapper<StockMsg>().eq(StockMsg::getCode, workReportId));
        isUpdate = Objects.nonNull(stockMsg);
        Date date = new Date();
        if (!isUpdate && difference.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }
        if (isUpdate) {
            StockDetail stockDetail = this.getOne(new LambdaQueryWrapper<StockDetail>().eq(StockDetail::getSmId, stockMsg.getId()).eq(StockDetail::getProductId, productId));
            if (Objects.nonNull(stockDetail)) {
                stockDetail.setHandleNum(stockDetail.getHandleNum().add(difference)).setUpdateTime(date);
                this.updateById(stockDetail);
            } else {
                stockMsgService.removeById(stockMsg.getId());
            }
        } else {
            stockMsg = new StockMsg().setType(3).setTime(new Date()).setCreateId(LoginUtil.getLoginUserId())
                    .setCreateTime(date).setCode(workReportId).setTypeOther("报工入库").setUpdateTime(date);
            stockMsgService.save(stockMsg);
            StockDetail stockDetail = new StockDetail().setSmId(stockMsg.getId()).setHandleNum(difference).setProductId(productId)
                    .setCreateId(LoginUtil.getLoginUserId()).setCreateTime(date).setUpdateTime(date);
            this.save(stockDetail);
        }
    }

    /**
     * 通过库存信息id删除库存详情
     */
    public void removeStockDetailByMsgId(List<Integer> stockIds) {
        this.remove(new LambdaQueryWrapper<StockDetail>().in(StockDetail::getSmId, stockIds));
    }


}
